<template>
  <view class="container">
    <FilterNavbar resetToInit title="选择车型" :searchList="searchList" v-model:queryParam="queryParam" @confirm="loadData"></FilterNavbar>
    <!-- 标签 -->
    <TagList :selectable="false" :statistics="statistics" />
    <!-- 列表内容 -->
    <view class="car-model-list">
      <CarModelItem
        selectable
        v-for="record in dataSource"
        :key="record.id"
        :record="record"
        :value="selectorId == record.id"
        @change="selectChange"
        @toDetail="toDetail"
      />
      <!-- 加载结束列表为空时展示 -->
      <ve-empty v-if="dataSource.length == 0 && loading == false"></ve-empty>
    </view>

    <ve-bottom-box>
      <ve-button type="primary" @click="onConfirm">确认</ve-button>
    </ve-bottom-box>

    <ve-confirm title="提示" v-model="confirmVisible" @confirm="onSubmit">
      <view>订单周期为: {{ orderRange }}</view>
      <view>您选择的车型已超卖</view>
      <view>请确认是否选择此车型？</view>
    </ve-confirm>
    <!-- 加载中tip -->
    <ve-toast ref="toastRef"></ve-toast>
  </view>
</template>

<script setup>
  import { ref, computed, nextTick } from 'vue'
  import { getCarModelStock } from '@/api/asset/car-stock'
  import { onLoad, onPullDownRefresh } from '@dcloudio/uni-app'
  import FilterNavbar from '@/components/FilterNavbar'
  import CarModelItem from './component/car-model-item.vue'
  import TagList from '../components/tag-list.vue'

  // 缓存传入信息
  let orderInfo = {
    startTime: '',
    endTime: '',
    siteId: '',
    siteName: '',
    modelId: '',
    modelName: '',
  }
  const searchList = computed(() => {
    return [
      {
        prop: 'siteId',
        label: '门店',
        type: 'remote-select',
        attrs: {
          params: { oldId: orderInfo.siteId },
          disabled: true,
          type: 'site',
          label: orderInfo.siteName,
          change: (form, labelForm, searchList, val) => {
            form.value.seriesIdList = undefined
            form.value.modelIdList = undefined
            labelForm.value.seriesIdList = undefined
            labelForm.value.modelIdList = undefined
            searchList.value[1].attrs.params.siteId = val
            searchList.value[2].attrs.params.siteId = val
          },
        },
      },
      {
        prop: 'seriesIdList',
        label: '车系',
        type: 'remote-select',
        attrs: {
          type: 'carSeries_site',
          multiple: true,
          params: {
            siteId: queryParam.value.siteId,
          },
          change: (form, labelForm, searchList, val) => {
            form.value.modelIdList = undefined
            labelForm.value.modelIdList = undefined
            searchList.value[2].attrs.params.seriesIdList = val
          },
        },
      },
      {
        prop: 'modelIdList',
        label: '车型',
        type: 'remote-select',
        attrs: {
          type: 'multiple_carModel_site',
          multiple: true,
          label: orderInfo.modelName,
          params: {
            siteId: queryParam.value.siteId,
            seriesIdList: queryParam.value.seriesIdList,
          },
        },
      },
      {
        prop: ['startTime', 'endTime'],
        label: '时间',
        type: 'daterange-picker',
      },
    ]
  })

  // 查询参数
  const queryParam = ref({
    siteId: undefined,
    seriesIdList: undefined,
    modelIdList: undefined,
    dateRange: [],
    startTime: '',
    endTime: '',
  })

  const dataSource = ref([])
  const statistics = ref({})
  const toastRef = ref()
  const loading = ref(true)
  const loadData = () => {
    toastRef.value.showLoading()
    getCarModelStock({ ...queryParam.value })
      .then((res) => {
        if (res.code == 200) {
          const result = res.result
          dataSource.value = result.list
          statistics.value = result.statistics
        }
      })
      .finally(() => {
        toastRef.value.hideLoading()
        loading.value = false
      })
  }

  const selectorId = ref()
  const selectChange = (record) => {
    selectorId.value = record.id
  }
  // 确认
  const confirmVisible = ref()
  const orderRange = ref('')
  let activedCarModel
  const onConfirm = () => {
    if (!selectorId.value) {
      uni.showToast({ title: '请先选择车型' })
      return
    }
    // 库存校验
    const query = orderInfo
    query.modelId = selectorId.value
    uni.showLoading()
    getCarModelStock(query).then((res) => {
      uni.hideLoading()
      const list = res.result.list
      activedCarModel = list[0]
      if (!activedCarModel) {
        return
      }
      const isMore = activedCarModel.useNum >= activedCarModel.stockNum
      if (isMore) {
        orderRange.value = `${query.startTime}-${query.endTime}`
        confirmVisible.value = true
      } else {
        onSubmit()
      }
    })
  }
  // 确认
  const onSubmit = () => {
    uni.$emit('carModelOk', activedCarModel)
    uni.navigateBack()
  }

  // 查看详情
  const toDetail = (record) => {
    let params = {
      ...queryParam.value,
      modelId: record.id,
    }
    uni.navigateTo({
      url: `/pages/asset/stock/model-stock/detail?params=${JSON.stringify(params)}`,
    })
  }

  // 接收参数
  onLoad((options) => {
    // 将 dateRange 进行JSON.parse
    let data = {
      ...options,
    }
    // 选中的值
    selectorId.value = data.modelId
    orderInfo = {
      startTime: data.startTime,
      endTime: data.endTime,
      siteId: data.siteId,
      siteName: data.siteName,
      modelName: data.modelName,
    }

    queryParam.value = {
      ...orderInfo,
    }
    if (data.modelId) {
      queryParam.value.modelIdList = [+data.modelId]
      queryParam.value.modelId = undefined
    }

    // 加载数据
    nextTick(() => {
      loadData()
    })
  })

  onPullDownRefresh(() => {
    loadData()
  })
</script>

<style lang="less" scoped>
  .container {
    height: auto;
    min-height: 100%;
  }
  .car-model-list {
    position: relative;
  }
</style>
